import { rander } from './rander'
import { popupManager } from "./popupManager";
import { popupNotification } from '../config/mapStyles';
import { layersManager } from "./layerManager";

// 函数: 拼接 modelId
const getModelId = (modelId: string, suffix: string) => `${modelId}${suffix}`;

// 函数: 更新航迹
function updateTrack(map: any, modelId: string, newPos: [number, number, number]) {
    const trackSource = map.getSource(getModelId(modelId, "_realTimePolyline"));
    if (trackSource) {
        let currentTrack = trackSource._data.features[0].geometry.coordinates;
        if (currentTrack.length > 1000) {
            currentTrack = currentTrack.filter((_: any, index: number) => index % 50 === 0);
        }
        currentTrack.push([newPos[0], newPos[1]]); // 更新航迹点

        trackSource.setData({
            type: 'FeatureCollection',
            features: [{
                type: 'Feature',
                geometry: {
                    type: 'LineString',
                    coordinates: currentTrack
                },
                properties: {

                }
            }]
        });
    } else {
        // 如果航迹图层不存在，创建航迹图层
        rander.geometryManager.drawPolyline(map, getModelId(modelId, "_realTimePolyline"), [newPos]);
    }
}

// 函数: 更新popup
function updatePopup(map: any, modelId: string, newPos: [number, number, number]) {
    const popupPosition: [number, number] = [newPos[0], newPos[1]];
    let popup = popupManager.getPopupById(getModelId(modelId, "_popup"));

    // 如果popup不存在，创建popup
    if (!popup) {
        popupManager.createPopup(map, getModelId(modelId, "_popup"), popupPosition, `<div>123</div>`);
    }

    // 更新popup位置与内容
    popupManager.updatePopupPositition(getModelId(modelId, "_popup"), popupPosition);
    const options = { longitude: newPos[0].toFixed(4), latitude: newPos[1].toFixed(4) };
    popupManager.updatePopup(popup, popupNotification.realTimeLayer(options));
}

// 计算方位角
function calculateBearing(start: [number, number], end: [number, number]): number {
    const [startLng, startLat] = start;
    const [endLng, endLat] = end;

    const dLng = (endLng - startLng) * Math.PI / 180;
    const startLatRad = startLat * Math.PI / 180;
    const endLatRad = endLat * Math.PI / 180;

    const y = Math.sin(dLng) * Math.cos(endLatRad);
    const x = Math.cos(startLatRad) * Math.sin(endLatRad) -
        Math.sin(startLatRad) * Math.cos(endLatRad) * Math.cos(dLng);

    let bearing = Math.atan2(y, x) * 180 / Math.PI;
    bearing = (bearing + 360) % 360; // 保证方位角在 0 到 360 度之间
    return bearing;
}

let requestAnimationFrameId: number ;
// 移动模型
function moveModel(map: any, modelId: string, targetPos: [number, number, number]) {
    // 获取当前模型的坐标
    let currentPos = map.getSource(getModelId(modelId, "_realTimeModel"))._data.features[0].geometry.coordinates as [number, number, number];
    currentPos = [Number(currentPos[0]), Number(currentPos[1]), Number(currentPos)];
    const step = 0.1;  // 移动步长

    // 计算当前位置到目标位置的增量
    const dLng = targetPos[0] - currentPos[0];
    const dLat = targetPos[1] - currentPos[1];
    const dAlt = targetPos[2] - currentPos[2];

    // 如果当前位置与目标位置接近，停止移动
    if (Math.abs(dLng) < 0.0001 && Math.abs(dLat) < 0.0001 && Math.abs(dAlt) < 0.1) {
        return;
    }

    // 更新当前位置
    currentPos[0] += dLng * step;
    currentPos[1] += dLat * step;
    currentPos[2] += dAlt * step;

    // 计算新的方位角
    // const newBearing = calculateBearing([currentPos[0], currentPos[1]], [targetPos[0], targetPos[1]]);

    // 更新标记图层的旋转角度
    // if (map.getLayer(getModelId(modelId, "_realTimeModel"))) {
    //     // map.setLayoutProperty(getModelId(modelId, "_realTimeModel"), 'icon-rotate', newBearing);
    // }

    // 更新模型数据
    map.getSource(getModelId(modelId, "_realTimeModel"))?.setData({
        type: 'FeatureCollection',
        features: [{
            type: 'Feature',
            geometry: {
                type: 'Point',
                coordinates: currentPos
            },
            properties: {

            }
        }]
    });

    // 更新航迹和popup
    updatePopup(map, modelId, currentPos);

    // 递归调用移动
    // requestAnimationFrameId = requestAnimationFrame(() => moveModel(map, modelId, targetPos));
}

// 函数: 检查模型是否存在，不存在则添加
function ensureModelExists(map: any, modelId: string, coordinates: [number, number, number]) {
    const modelExists = map.getSource(getModelId(modelId, "_realTimeModel"));
    if (!modelExists) {
        rander.geometryManager.drawPolyline(map, getModelId(modelId, "_realTimePolyline"), [coordinates]);
        rander.geometryManager.drawPoint(map, getModelId(modelId, "_realTimeModel"), coordinates);
    }
}

// 启动模型移动
export function startModelMovement(map: any, modelId: string, targetPos: [number, number, number]) {

    // 确保模型和航迹已添加到地图
    ensureModelExists(map, modelId, targetPos);
    // 开始移动
    moveModel(map, modelId, targetPos);
    updateTrack(map, modelId, targetPos);
}

// 移除模型和航迹和popup
export function removeModelAndTrack(map: any, modelId: string) {
    layersManager.removeLayer(map, getModelId(modelId, "_realTimeModel"));
    layersManager.removeLayer(map, getModelId(modelId, "_realTimePolyline"));
    // cancelAnimationFrame(requestAnimationFrameId)
    popupManager.closePopup(getModelId(modelId, "_popup"));

}

